//
//  NearShopViewController.m
//  FKGW
//
//  Created by song ce on 2017/2/17.
//  Copyright © 2017年 song ce. All rights reserved.
//

#import "NearShopViewController.h"
#import "NearShopCell.h"
#import "ShopDetailViewController.h"
#import "MJRefresh.h"
#define KpageNearCount   @"10"    //每页数据量
@interface NearShopViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,assign)NSInteger arrCount;//用于判断上拉加载更多是否有
@property(nonatomic,strong)UIImageView *no_DataIUmageV;
@property(nonatomic,assign)BOOL isNeedReloadData;
@end

@implementation NearShopViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //数据源
    self.dataSource = [NSMutableArray array];
       //表示图
     [self tableViewAndHeaderView];
      //返回顶部按钮
    [self backToTop];
    //加载数据
    [self loadData];
    //加载更多数据
//    [self loadMoreData];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(loadData) name:@"reLoadDataWhenLocationChanged" object:nil];
}

-(void)showTips{
       [MBProgressHUD showTipMessageInWindow:@"没有您的位置信息\r\n无法为您查询相关数据\r\n请到设置中修改定位权限"];
}
-(void)loadData{
    self.isNeedReloadData = YES;
     [self loadDataWithIndex:0 withPage:@"1"];
}


#pragma mark - 加载更多数据
- (void)loadMoreData{
    __weak typeof(self) weakSelf = self;
    self.index = 1;
    //上拉加载更多
    self.tableV.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        if(weakSelf.arrCount<[KpageNearCount intValue]){
            [weakSelf.tableV.mj_footer setState:MJRefreshStateNoMoreData];
        }else{
            self.index ++;
            NSString *page = [NSString stringWithFormat:@"%d",self.index];
            //参数2 代表操作的是上拉加载更多
            [weakSelf loadDataWithIndex:2 withPage:page];
        }
    }];
    
    //下拉刷新
    self.tableV.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.index = 1;
        [weakSelf loadDataWithIndex:1 withPage:@"1"];
    }];
}

//加载数据
- (void)loadDataWithIndex:(int)index withPage:(NSString*)page{
    if(!LONGITUDE.length){
        [self.view addSubview:self.no_DataIUmageV];
        [self performSelector:@selector(showTips) withObject:nil afterDelay:1];
        return;
    }
    [self.no_DataIUmageV removeFromSuperview];
    //2.60 附近接口--商场
    NSString *uid;
    if(USERID.length){
        uid = USERID;
    }else{
        uid = @"";
    }
    NSDictionary *paraDic = @{
                              @"userId":uid,
                              @"which":@"0",
                              @"lon":LONGITUDE,
                              @"lat":LATITUDE,
                              @"currentPage":page,
                              @"size":@"10",
                              @"industryId":@""
                              };
    if(index==0&&!self.isNeedReloadData){//第一次请求数据 使用这个进度条
      [MBProgressHUD showLoadingGif];
    }
    self.isNeedReloadData = NO;
    __weak typeof(self)  weakSelf = self;
    [Tools AFNetworkingRequestTypePostWithUrl:MYNEARBY paramters:paraDic  afterResultBlock:^(NSDictionary *resultDic) {
        DLog(@"附近接口--商场----%@",resultDic);
        if([resultDic[@"flag"] isEqualToString:@"true"]){
            NSArray *dataArr = resultDic[@"data"];
            if([dataArr isKindOfClass:[NSNull class]]) {
                if(index==0){
                    [MBProgressHUD dismissHUD];
                }
                if([weakSelf.tableV.mj_header isRefreshing]){
                    [weakSelf.tableV.mj_header endRefreshing];
                }
                if([weakSelf.tableV.mj_footer isRefreshing]){
                    [weakSelf.tableV.mj_footer endRefreshing];
                }
                return ;
            }
            NSMutableArray *startEndArr = [NSMutableArray array];
            for(NSDictionary *dic in dataArr){
                NearShopModel *model = [NearShopModel  modelWithDic:dic];
                model.isMarket = YES;
                [startEndArr addObject:model];
            }
            if(index==1&&weakSelf.dataSource.count>0){
                [weakSelf.dataSource removeAllObjects];
            }
            [weakSelf.dataSource addObjectsFromArray:startEndArr];
            weakSelf.arrCount = startEndArr.count;
            [weakSelf.tableV reloadData];
            if(weakSelf.dataSource.count){
                weakSelf.tableV.hidden = NO;
            }
            if(index==0){
                if(startEndArr.count==[KpageNearCount integerValue]){
                    //加载更多数据
                    [self loadMoreData];
                }else{
                    weakSelf.tableV.mj_header = nil;
                    weakSelf.tableV.mj_footer = nil;
                }

                [MBProgressHUD dismissHUD];
            }
            if([weakSelf.tableV.mj_header isRefreshing]){
                  [weakSelf.tableV.mj_header endRefreshing];
            }
            if([weakSelf.tableV.mj_footer isRefreshing]){
                [weakSelf.tableV.mj_footer endRefreshing];
            }
            if(weakSelf.arrCount<[KpageNearCount intValue]){
                [weakSelf.tableV.mj_footer setState:MJRefreshStateNoMoreData];
            }
        }else{
            if(resultDic[@"errorString"]){
                [MBProgressHUD showTipMessageInWindow:resultDic[@"errorString"]];
            }
        }
    }];
}

-(void)backToTop{
    UIButton *toTopButton = [UIButton buttonWithType:UIButtonTypeCustom];
    toTopButton.frame = CGRectMake(Main_Screen_Width-52, Main_Screen_Height-91-110, 42, 42);
    [toTopButton setImage:[UIImage imageNamed:@"button_zhiding_nor"] forState:UIControlStateNormal];
    [toTopButton addTarget:self action:@selector(BackAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:toTopButton];
    [self.view bringSubviewToFront:toTopButton];
}

-(void)BackAction{
    NSIndexPath *lastIndexPath=[NSIndexPath indexPathForRow:0 inSection:0];
    [self.tableV  scrollToRowAtIndexPath:lastIndexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

- (void)tableViewAndHeaderView{
    //表视图
    self.tableV  = [[UITableView alloc]initWithFrame:CGRectMake(0, 2, Main_Screen_Width, Main_Screen_Height-49-kNaviBarHeight-44-2) style:UITableViewStylePlain];
    self.tableV .showsVerticalScrollIndicator = NO;
    self.tableV .backgroundColor = DEF_COLOR242;
    self.tableV .delegate = self;
    self.tableV .dataSource =self;
    [self.view addSubview:self.tableV ];
      self.tableV .tableFooterView = [[UIView alloc]init];
    self.tableV.hidden = YES;
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *ident=@"acqtell";
    NearShopCell *cell=[tableView dequeueReusableCellWithIdentifier:ident];
    if(cell==nil){
        cell=[[[NSBundle mainBundle]loadNibNamed:@"NearShopCell" owner:self options:nil]lastObject];
    }
    cell.model = self.dataSource[indexPath.row];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 200;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NearShopModel *model = self.dataSource[indexPath.row];
    ShopDetailViewController  *shopDetail = [[ShopDetailViewController alloc]init];
    shopDetail.vcName = model.name;
    shopDetail.marketId = model.id;
    shopDetail.hidesBottomBarWhenPushed = YES;
    [[self secondNavigationController] pushViewController:shopDetail animated:YES];
}

- (BaseNavigationViewController*)secondNavigationController{
    UIResponder *next = self.nextResponder;
    while (next!=nil) {
        if([next isKindOfClass:[BaseNavigationViewController class]]){
            return (BaseNavigationViewController*)next;
        }
        next = next.nextResponder;
    }
    return nil;
}

-(UIImageView *)no_DataIUmageV{
    if(_no_DataIUmageV==nil){
        _no_DataIUmageV = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"icon_zanwushuju"]];
        _no_DataIUmageV.frame = CGRectMake((Main_Screen_Width-100)/2, Main_Screen_Height/2-60-44, 100, 115);
    }
    return _no_DataIUmageV;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
